﻿using AiQiuQuan.Sport.Model;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Text;

namespace AiQiuQuan.Sport.WebApi.Core
{
    /// <summary>
    /// swagger filter 描述
    /// </summary>
    public class EnumDocumentSchemaFilter : ISchemaFilter
    {
        /// <summary>
        /// 运用
        /// </summary>
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            var enumType = GetNullableEnum(context.Type);
            if (context.Type.IsEnum || enumType != null)
            {
                schema.Description = ToEnumDesc(enumType ?? context.Type);
                schema.Type = context.Type.IsEnum ? context.Type.Name : enumType.Name;
                schema.Format = schema.Type;
                EnumDescriptionList.Dic.TryAdd(schema.Type, schema.Description);
            }
        }

        #region private methods
        /// <summary>
        /// 获取可空类型枚举参数，无返回nu..
        /// </summary>
        private Type GetNullableEnum(Type type)
        {
            if (type.IsReferenceOrNullableType())
            {
                return type.GenericTypeArguments.FirstOrDefault(m => m.IsEnum);
            }

            return null;
        }

        /// <summary>
        /// 拼接信息
        /// </summary>
        private string ToEnumDesc(Type type)
        {
            var stringBuilder = new StringBuilder();
            Enum.GetNames(type)
                .ToList()
                .ForEach(name =>
                {
                    var e = (Enum)Enum.Parse(type, name);
                    var data = $"{Convert.ToInt64(Enum.Parse(type, name))} {e.ToEnumDescription()}、";

                    stringBuilder.Append(data);
                });
            return stringBuilder.ToString().TrimEnd('、');
        }
        #endregion
    }
}
